package pl.register.android.activities.gallery.logic;

import android.app.Activity;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Environment;
import android.provider.MediaStore;
import pl.register.android.activities.gallery.ui.StudentGalleryView;
import pl.register.android.gallery.LoadedImage;
import pl.register.android.storage.external.CourseRegisterSDCardManager;
import pl.register.android.student.Student;
import pl.register.android.util.database.DatabaseUtilLogger;

public class AsyncImagesLoader extends AsyncTask<Void, LoadedImage, Void> {

    private Activity activity;

    private StudentGalleryView galleryView;

    private Student student;

    public AsyncImagesLoader(Activity activity, Student student, StudentGalleryView galleryView) {
        this.activity = activity;
        this.student = student;
        this.galleryView = galleryView;
    }

    @Override
    protected Void doInBackground(Void... params) {
        String[] projection = {MediaStore.Images.Media._ID, MediaStore.Images.Media.DATA};
        String where = MediaStore.Images.Media.DATA +
                " LIKE '%" + CourseRegisterSDCardManager.getStudentGalleryFolderName(student) + "%'";
        Cursor cursor = activity.managedQuery(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, projection, where, null, null);
        while (cursor.moveToNext()) {
            int imageId = cursor.getInt(cursor.getColumnIndexOrThrow(MediaStore.Images.Media._ID));
            String path = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA));
            Uri uri = Uri.withAppendedPath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "" + imageId);
            publishProgress(new LoadedImage(imageId, uri, path));
        }
        cursor.close();
        return null;
    }

    @Override
    public void onProgressUpdate(LoadedImage... value) {
        System.out.println("Mattie prog");
        galleryView.addImage(value);
    }

}